﻿using CrowdPleaser.Core.Utilities;

namespace Behaving.Decorators
{
    // For each "run" of the parent node, the duration node will execute it's child
    // for the duration specified. After the duration has expired, it will return Success
    // unless RunningStateToReturnWhenDone is modified.
    public class Duration : Decorator, INotifyOnParentStop
    {
        private float? _startTime;

        public Duration(float runDuration, Behaviour behaviour)
            : base(behaviour)
        {
            RunDuration = runDuration;
            RunningStateToReturnWhenDone = RunningState.Success;
        }

        public float RunDuration { get; set; }

        public RunningState RunningStateToReturnWhenDone { get; set; }

        public Duration SetRunningStateToReturnWhenDone(RunningState runningState)
        {
            RunningStateToReturnWhenDone = runningState;
            return this;
        }

        public override RunningState Execute(BehaviourTree behaviourTree)
        {
            if (TimeManager.IsDoneWaiting(_startTime.Value + RunDuration))
            {
                return RunningStateToReturnWhenDone;
            }
            else
            {
                return Behaviour.Tick(behaviourTree);
            }
        }

        public override void Start(BehaviourTree behaviourTree)
        {
            _startTime = _startTime ?? TimeManager.CurrentTime;
            base.Start(behaviourTree);
        }

        public void ParentWasStopped(BehaviourTree behaviourTree, Behaviour behaviour)
        {
            _startTime = null;
        }
    }
}